package com.annie.piglatin;

public class PigLatinConverter {
	
	
	public static String convertToPigLatin(String sentence) throws StringFormatException
	 {
		  
		  //checks if the sentence is empty
		  if(sentence.trim().isEmpty())
		  {
		       throw new StringFormatException("There are no words to translate!");
	      }
		  //checks for invalid characters
		  boolean allowed = isAllowed(sentence);
		  if(!allowed){
			  throw new StringFormatException("Contains invalid characters!");
		  }
		
		  String result = "";
		  String word = "";
		  for(int i = 0; i < sentence.length(); i++){
			  if(isPunctuation(sentence.substring(i, i+1))){
				  result += intoPigLatin(word) + sentence.substring(i, i+1);
				  word = "";
			  }else{
				  word += sentence.substring(i, i+1);
			  }
		  }
		  
		  if(!word.isEmpty()){
			  result += intoPigLatin(word);
		  }
		  
		  return result;
	 }
	
	private static String intoPigLatin(String word) {
		if(word.isEmpty()){
			return word;
		}

		if(word.length() ==1){
			if(!isVowel(word)){
				return word + "ay";
			}else{
				return word + "way";
			}
		}

		String result = "";
		String end;
		if(!isVowel(word.substring(0,1))){
			int count = 1;
			for(int i = 1; i < word.length(); i++){
				if(!isVowel(word.substring(i, i+1))){
					count++;
				}else{
					break;
				}
			}
			result = word.substring(count, word.length()) + word.substring(0, count);
			end = "ay";
		}else{
			result = word.substring(1, word.length()) + word.substring(0, 1);
			end = "way";
		}
		
		if(result.length() > 2 && result.substring(0,1).equals(result.substring(1,2))){
			result = result.substring(1);
		}
		
		if(Character.isUpperCase(word.charAt(0))){
			result = result.toLowerCase();
			result = result.substring(0,1).toUpperCase() + result.substring(1);
		}
		
		return result + end;
	}
	
	
	
	
	private static boolean isVowel(String letter){
		return(letter.equalsIgnoreCase("a") || letter.equalsIgnoreCase("e") || letter.equalsIgnoreCase("i") || letter.equalsIgnoreCase("o") 
				|| letter.equalsIgnoreCase("u"));			
	}

	private static boolean isPunctuation(String letter) {
		return(letter.equals(" ") || letter.equals(".") || letter.equals(",") 
        		|| letter.equals("!") || letter.equals("?"));
	}

	private static boolean isAllowed(String sentence) {
	    for (int i = 0; i < sentence.length(); i++) {
	    	String cString = sentence.substring(i, i+1);
	        if(!Character.isLetter(cString.charAt(0)) && !isPunctuation(cString)){
	    	 	return false;
	        }
        }
	    return true;
	}
}
